using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SyncUdp
{
    using SyncUdp.Interface;
    using System;

    /// <summary>
    /// 存放单例的容器
    /// </summary>
    public static class IOCContainer
    {
        static Dictionary<Type, ISingleton> _singletonDic = new Dictionary<Type, ISingleton>();

        public static bool AddInstance(Type type, ISingleton singleton)
        {
            bool flag = _singletonDic.TryAdd(type, singleton);
            return flag;
        }

        public static bool AddInstance<T>(T singleton) where T : class, ISingleton
        {
            return AddInstance(typeof(T), singleton);
        }

        public static bool RemoveInstance<T>() where T : class, ISingleton
        {
            var t = typeof(T);
            if (_singletonDic.ContainsKey(t))
            {
                _singletonDic.Remove(t);
                return true;
            }
            return false;
        }

        public static T GetInstance<T>() where T : class, ISingleton
        {
            bool flag = _singletonDic.TryGetValue(typeof(T), out var singleton);
            return flag ? (T)singleton.Instance : null;
        }

        /// <summary>
        /// 初始化所有单例
        /// </summary>
        public static void InitSingletons()
        {
            foreach (var singleton in _singletonDic.Values)
                singleton.Init();
        }
    }
}
